package yxy.game.pm2.module.soloride;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.soloridefirstreward;
import yxy.game.pm2.bean.currency.Currencies;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.module.battle.BattleModule;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 千里走单骑
 */
public class SoloRideModule extends PlayerModule {
    // bean===========================================================================

    private int best;// 最高通关
    private int today;// 今日最高通关
    private int current;// 当前通关
    private int start;// 挑战起始关

    private int box;// 已经领取的宝箱

    private boolean battling;

    private SoloRideHero hero;// 正在战斗的武将
    private LinkedList<String> battles = new LinkedList<>();
    private Currencies rewards = new Currencies();

    private DateTime tickTime;// 打点时间

    private DateTime updateTime;

    public int getBest() {
        return best;
    }

    public void setBest(int best) {
        this.best = best;
    }

    public int getToday() {
        return today;
    }

    public void setToday(int today) {
        this.today = today;
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getCurrent() {
        return current;
    }

    public void setCurrent(int current) {
        this.current = current;
    }

    public int getBox() {
        return box;
    }

    public void setBox(int box) {
        this.box = box;
    }

    public boolean isBattling() {
        return battling;
    }

    public void setBattling(boolean battling) {
        this.battling = battling;
    }

    public SoloRideHero getHero() {
        return hero;
    }

    public void setHero(SoloRideHero hero) {
        this.hero = hero;
    }

    public LinkedList<String> getBattles() {
        return battles;
    }

    public void setBattles(LinkedList<String> battles) {
        this.battles = battles;
    }

    public Currencies getRewards() {
        return rewards;
    }

    public void setRewards(Currencies rewards) {
        this.rewards = rewards;
    }

    public DateTime getTickTime() {
        return tickTime;
    }

    public void setTickTime(DateTime tickTime) {
        this.tickTime = tickTime;
    }

    public DateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(DateTime updateTime) {
        this.updateTime = updateTime;
    }

    // func===========================================================================

    /**
     * 刷新每日的状态
     */
    private void update() {
        try {
            if (tryLock()) {
                DateTime now = DateTime.now();
                if (!new LocalDate(now).equals(new LocalDate(getUpdateTime()))) {
                    setUpdateTime(now);
                    setToday(0);
                    set();
                }
                if (isBattling()) {
                    BattleModule battleModule = BattleModule.get(getPlayerCode(), SoloRideHandle.battleCode(0));
                    if (battleModule == null) {
                        setBattling(false);
                        setHero(null);
                        getBattles().clear();
                        getRewards().clear();
                        setCurrent(0);
                        set();
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            unlock();
        }
    }

    /**
     * 起始关卡
     */
    public int startStage() {
        int start = getBest() - getBest() % 10;
        start = start <= 0 ? 0 : start;
        if (getStart() != start + 1) {
            setStart(start + 1);
            set();
        }
        return getStart();
    }

    public Iterable<? extends Integer> rewardBox() {
        ArrayList<Integer> boxList = new ArrayList<>();
        for (int i = getBox(); i <= getBest(); i++) {
            soloridefirstreward data = DataCenter.getData(i, soloridefirstreward.class);
            if (data == null) {
                continue;
            }
            if (getBox() >= data.getId()) {
                continue;
            }
            boxList.add(data.getId());
            return boxList;
        }
        return boxList;
    }

    public void best(int stage) {
        if (getBest() < stage) {
            setBest(stage);
//			TaskHandle.handle(getPlayerCode(), TaskType.指标型_神将试炼_通关_达到, stage);
        }
    }

    public void pass(int stage) {
//		if (getToday() < stage && stage >= getStart()) {
//			setToday(stage);
//			RankSoloRide.getRank(getPlayerCode()).put(getPlayerCode(), stage);
//		}

        //合区的兼容处理
        RankSoloRide rank = RankSoloRide.getRank(getPlayerCode());
        if (rank == null || getToday() < stage && stage >= getStart()) {
            setToday(stage);
            RankSoloRide.getRank(getPlayerCode()).put(getPlayerCode(), stage);
        }

        if (getBest() < stage) {
            setBest(stage);
//			TaskHandle.handle(getPlayerCode(), TaskType.指标型_神将试炼_通关_达到, stage);
        }
        int start = getBest() - getBest() % 10;
        start = start <= 0 ? 0 : start;
        setStart(start + 1);
    }

    // redis==========================================================================
    private static String key(String playerCode) {
        return String.format("PLAYER:%s:MODULE:SOLORIDE", playerCode);
    }

    public void set() {
        try {
            setv(key(getPlayerCode()), this);

            new TipHandle().updateTip(getPlayerCode(), TipType.历练_千里单骑切页, isBattling());// 红点提示
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    static public SoloRideModule get(String playerCode) {
        try {
            SoloRideModule module = getv(key(playerCode));
            if (module == null) {
                module = MySQLCacheDAO.getV(key(playerCode), SoloRideModule.class);
                if (module != null) {
                    module.set();
                }//把数据同步到redis
            }

            if (module == null) {
                module = create(playerCode);
            }
            module.update();
            return module;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static private SoloRideModule create(String playerCode) {
        SoloRideModule module = new SoloRideModule();
        module.setUpdateTime(DateTime.now());
        module.setTickTime(DateTime.now());
        module.setPlayerCode(playerCode);
        module.set();
        return module;
    }

    //存储到数据库的方法
    public static void saveToDB(String playerCode) {
        try {
            String key = key(playerCode);
            if (touchBucket(key).isExists()) {
                SoloRideModule soloRideModule = getv(key(playerCode));
                if (soloRideModule != null) MySQLCacheDAO.setV(key, soloRideModule);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //从redis移走数据的操作
    public static void removeAllFromRedis(String playerCode) {
        try {
            touchBucket(key(playerCode)).delete();
        } catch (RedisException e) {
            e.printStackTrace();
        }
    }

    // lock==========================================================================

    @Override
    public String lockKey() {
        return String.format("lock:%s", key(getPlayerCode()));
    }


    //删除
    public static void deleteFromTable(String playerCode) {
        try {
            String key = key(playerCode);
            MySQLCacheDAO.delete(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
